﻿using Autofac;
using Autofac.Extensions.DependencyInjection;
using Autofac.Extras.DynamicProxy;
using ESoft.Core.Interceptor;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;

namespace ESoft.Core.Util.Helpers
{
    public class AutoFaceHelper
    {
        public static IContainer BuildServiceContainer(IServiceCollection services, Assembly[] assmblyArr,Action<ContainerBuilder> action)
        {
            var builder = new ContainerBuilder();
            builder.RegisterType<TransactionInterceptor>();

            builder.RegisterAssemblyTypes(assmblyArr).Where(t => t.Name.EndsWith("Dao",StringComparison.CurrentCultureIgnoreCase)).AsImplementedInterfaces().EnableInterfaceInterceptors().InterceptedBy(typeof(TransactionInterceptor));

            builder.RegisterAssemblyTypes(assmblyArr)
                .Where(t => t.Name.EndsWith("Service", StringComparison.CurrentCultureIgnoreCase)).AsImplementedInterfaces()
                .EnableInterfaceInterceptors().InterceptedBy(typeof(TransactionInterceptor));
            action?.Invoke(builder);

            builder.Populate(services);
            var ApplicationContainer = builder.Build();
            return ApplicationContainer;
        }
    }
}
